package cn.wolfcode.web.controller;

import cn.wolfcode.qo.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {


    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult login(String username, String password) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            SecurityUtils.getSubject().login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }
//        try {
//            //对密码进行加密(把用户名当做盐)
//            Md5Hash md5Hash = new Md5Hash(username, password);
//            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());
//            System.out.println(token);
//            SecurityUtils.getSubject().login(token);
//            return new JsonResult();
//        } catch (UnknownAccountException e) {
//            return new JsonResult(false, "账号不存在");
//        }
    }

    @RequestMapping("/userLogout")
    public String nopermission(HttpSession session) {
        return "redirect:/login.html";
    }

}
